package com.digiwin.demo.influx;

import org.influxdb.BatchOptions;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.influxdb.impl.InfluxDBResultMapper;

import java.util.List;

/**
 * @Author yanggld
 * @Date 2020/1/2-16:47
 * @Description
 */
// influxDb操作类
public class SimpleInfluxTemplate implements InfluxTemplate {

	private final InfluxDB db;

	public SimpleInfluxTemplate(InfluxBean bean){
		this.db= InfluxDBFactory.connect(bean.getUrl(), bean.getUsername(), bean.getPassword());
		db.setDatabase(bean.getDbName());
		db.enableBatch(BatchOptions.DEFAULTS.exceptionHandler(
				(failedPoints, throwable) -> {
					/* custom error handling here */ })
				.consistency(InfluxDB.ConsistencyLevel.ALL)
				.bufferLimit(100)
		);
	}

	@Override
	public void write(Point point) {
		db.write(point);
	}

	@Override
	public void bentchWrite(BatchPoints points) {
		db.write(points);
	}

	@Override
	public <T> List<T> query(Query query, Class<T> tClass) {
		QueryResult result=db.query(query);
		InfluxDBResultMapper resultMapper = new InfluxDBResultMapper(); // thread-safe - can be reused
		return resultMapper.toPOJO(result, tClass);
	}

	@Override
	public void close() {
		db.close();
	}
}
